import json

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import time

from wsmud_tuiyan_web.service.wsgameLogin import GetLoginInfo
from wsmud_tuiyan_web.service.wsgamePlayer import wsgamePlayer
from wsmud_tuiyan_web.service.wstuiyan import wsinfer
from wsmud_tuiyan_web.data import attributes_data
from wsmud_tuiyan_web.data import cache

@csrf_exempt
def index(request):
    if request.method == 'POST':
        param_body = request.body
        param = json.loads(param_body)

        attr=[]
        if "attributes" in param:
            attr=param['attributes'].split(',')

        userInfo = {
            "account": param['account'],  # 帐号
            "password": param['password'],  # 密码
            "zone": param['zone'],  # 区服
            "player": param['player'],  # 角色名
            "book": param['book'],  # 自创秘籍名称
            "position": param['position'],  # 推演位置 : force unarmed dodge staff throwing parry sword blade club whip
            "attributes": attr,  # 想要附加的属性或词条，目前支持 ：冷却百分比 冷却时间 破防 终伤 臂力 暴击 暴击伤害 命中 命中百分比 攻击 攻击百分比 剑心 不灭 战神  移花
            "continuation": param['continuation'] == "True",  # 是否连续跳到指定的总次数 True：连续跳，不中断， False： 根据配置的step中断
            "total": int(param['total']),  # 总次数
            "step": int(param['step']),  # 每step次中断一次，continuation=False 时可用
            "feiyiId": param['feiyiId'],  # 有没有飞翼剑   False 无   True 有
            "haveBingxin": param['haveBingxin'] == "True"  # 有没有冰心丹   False 无   True 有
        }
        c = GetLoginInfo(userInfo["account"], userInfo["password"])
        c.getServer()
        utoken = c.getCookie()
        serverurl = c.getServerUrl(userInfo["zone"])
        userInfo["acctoken"] = utoken
        userInfo["serverip"] = serverurl
        wsp = wsgamePlayer(serverurl, utoken)
        wsp.start()
        while (wsp.getStatic()):
            time.sleep(1)
        userlist = wsp.getRoles()
        for role in userlist:
            if userInfo["player"] == role["name"]:
                userInfo["player"] = role["id"]
                break
        wsg = wsinfer(userInfo)
        wsg.start()
        return HttpResponse(userInfo["player"])

@csrf_exempt
def attributes(request):
    return HttpResponse(json.dumps(attributes_data.getAttrsFromGitee(), ensure_ascii=False), content_type="application/json,charset=utf-8")

@csrf_exempt
def log(request):
    if request.method == 'GET':
        player = request.GET.get('player', default='none')
    if player != 'none' and player in cache.cache:
        return HttpResponse(json.dumps(cache.cache[player], ensure_ascii=False),
                            content_type="application/json,charset=utf-8")
    return HttpResponse(json.dumps({"noPlayer": 1}, ensure_ascii=False),
                            content_type="application/json,charset=utf-8")
